package com.xch.sboot.common.util;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * HmacSHA256签名算法
 * @author xch
 * @date 2021/12/17 16:51
 */
public class HmacSHA {

    private static final String ALGORITHM_NAME = "HmacSHA256";

    public static String signString(String stringToSign, String accessKeySecret) {
        try {
            Mac hmacSha256 = Mac.getInstance(ALGORITHM_NAME);
            SecretKeySpec secretKey = new SecretKeySpec(accessKeySecret.getBytes(), ALGORITHM_NAME);
            hmacSha256.init(secretKey);
            return DatatypeConverter.printBase64Binary(hmacSha256.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

}
